package net.sample.gismeteo.net;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import net.sample.gismeteo.WeatherInfo;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 
 * @author vkozlov
 * @version $Id: $
 */
public class WeatherXMLParser extends DefaultHandler {
	List<WeatherInfo> result;
	WeatherInfo weatherInfo;
	
	@Override
	public void startElement(String uri, String name, String qName, Attributes attrs) {
		if (name.toUpperCase().equals("FORECAST")) {
			weatherInfo = new WeatherInfo();
			weatherInfo.setDay(Integer.parseInt(attrs.getValue("day")));
			weatherInfo.setMonth(Integer.parseInt(attrs.getValue("month")));
			weatherInfo.setYear(Integer.parseInt(attrs.getValue("year")));
			weatherInfo.setHour(Integer.parseInt(attrs.getValue("hour")));
			weatherInfo.setTod(Integer.parseInt(attrs.getValue("tod")));
			weatherInfo.setWeekday(Integer.parseInt(attrs.getValue("weekday")));
		}
		if (name.toUpperCase().equals("PHENOMENA")) {
			weatherInfo.setCloudiness(Integer.parseInt(attrs.getValue("cloudiness")));
			weatherInfo.setPrecipitation(Integer.parseInt(attrs.getValue("precipitation")));
		}
		if (name.toUpperCase().equals("PRESSURE")) {
			weatherInfo.setPressureMax(attrs.getValue("max"));
			weatherInfo.setPressureMin(attrs.getValue("min"));
		}
		if (name.toUpperCase().equals("TEMPERATURE")) {
			weatherInfo.setTemperatureMax(attrs.getValue("max"));
			weatherInfo.setTemperatureMin(attrs.getValue("min"));
		}
		if (name.toUpperCase().equals("WIND")) {
			weatherInfo.setWindMax(attrs.getValue("max"));
			weatherInfo.setWindMin(attrs.getValue("min"));
			weatherInfo.setWindDir(Integer.parseInt(attrs.getValue("direction")));
		}
		if (name.toUpperCase().equals("RELWET")) {
			weatherInfo.setRelwetMax(attrs.getValue("max"));
			weatherInfo.setRelwetMin(attrs.getValue("min"));
		}
	}
	
	@Override
	public void endElement(String uri, String name, String qName) throws SAXException {
		if (name.toUpperCase().equals("FORECAST")) {
			result.add(weatherInfo);
		}
	}
	
	public List<WeatherInfo> parse(String weatherXML) throws ParserConfigurationException, SAXException, IOException {
		result = new ArrayList<WeatherInfo>();
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		xr.setContentHandler(this);
		xr.parse(new InputSource(new StringReader(weatherXML)));
		return result;
	}
	
}
